package com.example.pceb.log;

import ch.qos.logback.core.AppenderBase;
import ch.qos.logback.classic.spi.ILoggingEvent;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.beans.factory.annotation.Autowired;
import com.example.pceb.log.SpringContextHolder;

@Component
public class DBLogAppender extends AppenderBase<ILoggingEvent> {

    private JdbcTemplate jdbcTemplate;

    private JdbcTemplate getJdbcTemplate() {
        if (jdbcTemplate == null) {
            jdbcTemplate = SpringContextHolder.getBean(JdbcTemplate.class);
        }
        return jdbcTemplate;
    }

    @Override
    protected void append(ILoggingEvent eventObject) {
        try {
            JdbcTemplate jdbcTemplate = getJdbcTemplate();
            if (jdbcTemplate == null) return; // Spring还没初始化好
            String level = eventObject.getLevel().toString();
            String message = eventObject.getFormattedMessage();
            String exception = eventObject.getThrowableProxy() != null ? eventObject.getThrowableProxy().getMessage() : null;
            String operator = eventObject.getLoggerName();
            String sql = "INSERT INTO system_log (level, message, exception, operator, create_time) VALUES (?, ?, ?, ?, NOW())";
            jdbcTemplate.update(sql, level, message, exception, operator);
        } catch (Exception e) {
            // 防止日志写入异常导致死循环
            System.err.println("DBLogAppender写入日志失败: " + e.getMessage());
        }
    }
} 